#region Summary

// 
// Owner : JackieHan 
// 
// Solution : DailyCollection 
// 
// Project : Jackie.Utility.Notify.Domain
// 
// File : MessageManager.cs
// 
// CopyRight : Copyright © 2010-2011 Skomart Corporation, All Rights Reserved 
// 
// Summary : 消息管理器
// 
// History : 
//			2011-04-28 14:48:49	    Create 
// 

#endregion

#region Using

using System;
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using Common.Logging;
using Jackie.Utility.CustomExtension;
using Jackie.Utility.Notify.Domain;
using Jackie.Utility.Notify.Services.Manager.Sender;

#endregion

namespace Jackie.Utility.Notify.Services.Manager
{
    /// <summary> 
    /// 消息管理器
    /// </summary>
    public class MessageManager
    {
        #region Singleton

        private static readonly object LockObject = new object();
        private static MessageManager instance;

        public static MessageManager GetInstance()
        {
            if (instance == null)
            {
                lock (LockObject)
                {
                    if (instance == null)
                        instance = new MessageManager();
                }
            }
            return instance;
        }

        #endregion

        /// <summary>
        /// 所有消息的历史记录
        /// </summary>
        private readonly IDictionary<MessageInfo, MessageHistoryInfo> messagesHistory;
        /// <summary>
        /// 所有消息标题下的所有消息
        /// </summary>
        private readonly IDictionary<TitleInfo, List<MessageInfo>> titlesMessages;
        /// <summary>
        /// 消息发送实现
        /// </summary>
        private readonly IMessageSender messageSender;
        /// <summary>
        /// 日志记录
        /// </summary>
        private readonly ILog logger;

        private MessageManager()
        {
            logger = LogManager.GetLogger(GetType());
            messagesHistory = new Dictionary<MessageInfo, MessageHistoryInfo>();
            titlesMessages = new Dictionary<TitleInfo, List<MessageInfo>>();
            ///TODO:这个需要完善
            messageSender = new ImmediatelySender();
        }

        /// <summary>
        /// 发送保持连接活动的消息
        /// </summary>
        public void SendKeepAliveMessage()
        {
            logger.Info("start send keep alive message");
            try
            {
                messageSender.Send(GetKeepAliveMessage());
            }
            catch (Exception ex)
            {
                logger.Error("send keep alive message error!", ex);
            }

            logger.Info("end sended");
        }

        private MessageInfo GetKeepAliveMessage()
        {
            var titleManager = TitleManager.GetInstance();
            var title = titleManager.GetKeepAliveTitle();
            var message = new MessageInfo { Code = "KeepAliveMessasge", Message = "保持连接", TitleCode = title.Code };

            return message;
        }

        /// <summary>
        /// 发送对于某个客户端每口发送的全部消息
        /// </summary>
        /// <param name="title">消息标题</param>
        /// <param name="client">订阅消息客户端</param>
        public void SendNotSendMessage(TitleInfo title, ClientSubscribeInfo client)
        {
            var messages = GetNotSendMessages(title, client);
            messages.ForEach(item => messageSender.Send(item, client));
        }


        /// <summary>
        /// 获取待发送的消息
        /// </summary>
        /// <param name="client">客户端信息</param>
        /// <param name="title">消息标题</param>
        /// <returns></returns>
        private List<MessageInfo> GetNotSendMessages(TitleInfo title, ClientSubscribeInfo client)
        {
            if (!titlesMessages.ContainsKey(title))
                return new List<MessageInfo>();
            var messages = titlesMessages[title];
            return (from message in messages
                    let history = messagesHistory[message]
                    where !history.IsSend(client)
                    select message).ToList();
        }

        /// <summary>
        /// 清理掉所有已发送的消息
        /// </summary>
        public void CleanSendedMessage()
        {

        }


        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="info">消息</param>
        public void SendMessage(MessageInfo info)
        {
            InitializeMessageReceiveHistory(info);

            MessagesTitlesProcess(info);

            //发送消息
            logger.Info(string.Format("start send normal message[{0}]!", info));
            messageSender.Send(info);
            logger.Info("end sended!");
        }

        /// <summary>
        /// 记录消息标题下的所有消息
        /// </summary>
        /// <param name="info"></param>
        private void MessagesTitlesProcess(MessageInfo info)
        {
            var titleManager = TitleManager.GetInstance();
            var title = titleManager.GetTitle(info.TitleCode);
            if (titlesMessages.ContainsKey(title))
            {
                var messages = titlesMessages[title];
                messages.Add(info);
            }
            else
            {
                titlesMessages.Add(title, new List<MessageInfo> { info });
            }
        }

        /// <summary>
        /// 初始化消息接收历史信息
        /// </summary>
        /// <param name="info">消息</param>
        private void InitializeMessageReceiveHistory(MessageInfo info)
        {
            var history = new MessageHistoryInfo() { Message = info, ReceivedTime = DateTime.Now };
            messagesHistory.Add(info, history);
        }

        /// <summary>
        /// 添加消息发送历史信息
        /// </summary>
        /// <param name="info">消息</param>
        /// <param name="sendInfo">发送信息</param>
        public void AddMessageSendedHistory(MessageInfo info, MessageSendInfo sendInfo)
        {
            var history = messagesHistory[info];
            history.SendedHistory.Add(sendInfo);
        }


    }
}